package com.kedou.sdk.download;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.FileProvider;

import com.kedou.sdk.utils.WL;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDownloader implements OnDownloadListener {

    private static final String TAG = BaseDownloader.class.getSimpleName();

    private final List<OnDownloadListener> mCallbackArray;
    private DownloadManager downloadManager;
    private Context context;

    BaseDownloader() {
        this.mCallbackArray = new ArrayList<>();
    }

    protected Context getApplicationContext() {
        return context;
    }

    public void init(Context context) {
        this.context = context.getApplicationContext();

        if (downloadManager == null) {
            downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        }
    }

    public void addOnDownloadListener(OnDownloadListener listener) {
        if (!mCallbackArray.contains(listener)) {
            mCallbackArray.add(listener);
        }
    }

    public void removeOnDownloadListener(OnDownloadListener listener) {
        if (mCallbackArray.contains(listener)) {
            mCallbackArray.remove(listener);
        }
    }

    public File getExternalDownloadDir() {
        if (context != null) {
            return context.getExternalCacheDir();
        }
        return Environment.getDownloadCacheDirectory();
    }

    public abstract File getDownloadApkVersionFile();

    public abstract File randomMakeDownloadStorageFile(String extension);

    public boolean isDownloading(long downloadId) {
        DownloadInfo downloadInfo = DownloadInfo.queryDownloadInfo(downloadManager, downloadId);

        return DownloadManager.STATUS_PAUSED >= downloadInfo.downloadStatus
                && DownloadManager.STATUS_PENDING <= downloadInfo.downloadStatus;
    }

    public boolean checkDownloadFileCompletedStatus(long downloadId) {
        DownloadInfo downloadInfo = DownloadInfo.queryDownloadInfo(downloadManager, downloadId);

        return downloadInfo.downloadedBytes == downloadInfo.downloadTotalBytes
                && DownloadManager.STATUS_SUCCESSFUL >= downloadInfo.downloadStatus;
    }

    public long startVersionDownloadTask(String downloadUrl, File storageFile, String title, String description, boolean notificationVisible) {
        long downloadId = 0;

        WL.i(TAG, "startVersionDownloadTask ======>start download process.");

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        request.setAllowedOverRoaming(false);

        if (notificationVisible) {
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle(title);
            request.setDescription(description);
            request.setVisibleInDownloadsUi(true);
        } else {
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        }

        request.setDestinationUri(Uri.fromFile(storageFile));

        if (downloadManager != null) {
            downloadId = downloadManager.enqueue(request);

            DownloadScheduleTimer scheduleTimer = new DownloadScheduleTimer(downloadManager, downloadId, storageFile);
            scheduleTimer.setOnVersionUpdateListener(this);
            scheduleTimer.execute();
        }
        WL.i(TAG, "startVersionDownloadTask =========> downloadId: " + downloadId);

        return downloadId;
    }

    public final void startVersionInstallTask(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Uri apkUri;

        if (file == null && !file.exists()) {
            WL.i(TAG, "startVersionInstallTask ========> file is not exists");
            return;
        }

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = new StringBuilder(context.getPackageName()).append(".fileProvider").toString();
            apkUri = FileProvider.getUriForFile(context, authority, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(file);
        }

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public final void clearHistoryDownload() {
        File tempFile = randomMakeDownloadStorageFile("ada");
        new DownloadScheduleTimer(downloadManager, 0, tempFile).execute();
    }

    @Override
    public final void onDownloadProgress(long downloadId, long updateSize, long totalSize) {
        for (OnDownloadListener listener : mCallbackArray) {
            listener.onDownloadProgress(downloadId, updateSize, totalSize);
        }
    }

    @Override
    public final void onDownloadCompleted(long downloadId, File file) {
        for (OnDownloadListener listener : mCallbackArray) {
            listener.onDownloadCompleted(downloadId, file);
        }
    }

    @Override
    public final void onDownloadError(long downloadId) {
        for (OnDownloadListener listener : mCallbackArray) {
            listener.onDownloadError(downloadId);
        }
    }
}
